#include <stdio.h>

#include "gm_monitor.h"

void init_monitor_list_node(struct list_head* list)
{
	ptask t;
	struct list_head* node;
	list_for_each(node, list) {
		t = container_of(node, task, thisnode);
		t->init(&(t->mn), t->ignore);
	}
}

void update_monitor_list_node(struct list_head* list, cJSON* root) 
{
	ptask t;
	struct list_head* node;
	list_for_each(node, list) {
		t = container_of(node, task, thisnode);
		if (t->uf != 0) {
			if (t->cu < t->uf) {
				t->cu++;
				continue;
			}
			t->cu = 0;
		}
		t->update(&(t->mn));
		if (t->correction_value && t->correction) {
			t->correction(t->correction_value());
		}
		if (t->json == NULL) {
			t->json = cJSON_CreateObject();
			cJSON_AddItemToObject(root, t->name, t->json);
		}
		t->to_json(t->json);
	}
}

void update_monitor_list_node_text(struct list_head* list, char* buffer, uint32_t size)
{
        ptask t;
        struct list_head* node;
	uint32_t k1 = 0, k2 = size, r;
        list_for_each(node, list) {
                t = container_of(node, task, thisnode);
                if (t->uf != 0) {
                        if (t->cu < t->uf) {
                                t->cu++;
                                continue;
                        }
                        t->cu = 0;
                }
                t->update(&(t->mn));
                if (t->correction_value && t->correction) {
                        t->correction(t->correction_value());
                }
		if (t->to_text && k2 > 0) {
			r = t->to_text(buffer + k1, k2);
			k1 += r;
			k2 -= r;
		}
		if (k2 <= 0) break;
        }
}


void clean_monitor_list_node(struct list_head* list) 
{
	ptask t;
	struct list_head* node;
	list_for_each(node, list) {
		t = container_of(node, task, thisnode);
		t->clean();
		free(t->mn);
	}

}

